#include "LineSegment.h"

LineSegment::LineSegment(const float fromX, const float fromY, const float toX, const float toY)
{
	from.x = fromX;
	from.y = fromY;

	to.x = toX;
	to.y = toY;

	// calculer la normal.
	Vector2D vec;
	vec.x = to.x - from.x;
	vec.y = to.y - from.y;

	normal.x = -vec.y;
	normal.y =  vec.x;
}

LineSegment::LineSegment(const Vector2D &from, const Vector2D &to)
{
	LineSegment(from.x, from.y, to.x, to.y);
}


bool LineSegment::IntersectsWith(const LineSegment &seg) const
{
	float x1 = from.x, x2 = to.x, x3 = seg.from.x, x4 = seg.to.x;
	float y1 = from.y, y2 = to.y, y3 = seg.from.y, y4 = seg.to.y;
 
	float d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
	// If d is zero, there is no intersection
	if (d == 0) return false;
 
	// Get the x and y
	float pre = (x1*y2 - y1*x2), post = (x3*y4 - y3*x4);
	float x = ( pre * (x3 - x4) - (x1 - x2) * post ) / d;
	float y = ( pre * (y3 - y4) - (y1 - y2) * post ) / d;
 
	// Check if the x and y coordinates are within both lines
	if ( x < std::min(x1, x2) || x > std::max(x1, x2) ||
	x < std::min(x3, x4) || x > std::max(x3, x4) ) return false;
	if ( y < std::min(y1, y2) || y > std::max(y1, y2) ||
	y < std::min(y3, y4) || y > std::max(y3, y4) ) return false;
 
	// Return the point of intersection
	return true;
}